package com.chuangjiangx.member.coupon.ddd.domain.service;

import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.commons.wx.upload.WxUploadUtils;
import com.chuangjiangx.member.coupon.ddd.domain.model.*;
import com.chuangjiangx.member.coupon.ddd.domain.repository.MbrConfigRepository;
import com.chuangjiangx.member.coupon.ddd.domain.repository.MbrPayGiftCardRuleRepository;
import com.chuangjiangx.member.coupon.ddd.domain.repository.MbrWxCardRepository;
import com.chuangjiangx.member.stored.ddd.dal.mapper.MbrOrderPayDalMapper;
import com.chuangjiangx.member.basic.ddd.dal.mapper.WXPublicUserInfoDalMapper;
import com.chuangjiangx.member.basic.ddd.dal.dto.AgentWXPublicUserInfo;
import com.chuangjiangx.member.stored.ddd.dal.dto.OrderPay;
import com.chuangjiangx.member.coupon.ddd.domain.service.command.CreateCard;
import com.chuangjiangx.member.coupon.ddd.domain.service.command.CreateWxCard;
import com.chuangjiangx.member.coupon.ddd.domain.service.command.UpdateCard;
import com.chuangjiangx.member.coupon.ddd.domain.service.command.UpdateWxCard;
import com.chuangjiangx.member.coupon.ddd.domain.repository.MbrCouponRepository;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrAccount;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrUserMappingRepository;
import com.chuangjiangx.member.basic.ddd.domain.model.Member;
import com.chuangjiangx.member.basic.ddd.domain.model.MemberRepository;
import com.chuangjiangx.member.basic.ddd.domain.service.MemberRedisDomainService;
import com.chuangjiangx.member.basic.ddd.domain.model.MerchantId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import weixin.popular.api.CardAPI;
import weixin.popular.bean.card.create.CreateResult;
import weixin.popular.bean.card.get.GetMemberCardResult;
import weixin.popular.bean.card.get.GetResult;
import weixin.popular.bean.card.membercard.create.*;
import weixin.popular.bean.card.membercard.update.UpdateMemberCard;
import weixin.popular.bean.card.membercard.updatememberinfo.UpdateMemberInfo;
import weixin.popular.bean.card.membercard.updatememberinfo.UpdateMemberInfoResult;
import weixin.popular.bean.card.update.UpdateResult;
import weixin.popular.util.JsonUtil;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.function.Consumer;

/**
 * 会员卡domainService
 *
 * @author wp
 * @date 2018-08-30 13:46
 **/
@Service
@Slf4j
public class MbrCardDomainService {

    @Value("${member.h5.domain:''}")
    private String memberH5Url;

    private final MbrCouponRepository mbrCouponRepository;
    private final MbrConfigRepository mbrConfigRepository;
    private final MbrWxCardRepository mbrWxCardRepository;
    private final WXPublicUserInfoDalMapper wxPublicUserInfoDalMapper;
    private final MemberRedisDomainService memberRedisDomainService;
    private final MbrPayGiftCardRuleRepository mbrPayGiftCardRuleRepository;
    private final MbrOrderPayDalMapper mbrOrderPayDalMapper;
    private final MemberRepository memberRepository;
    private final MbrUserMappingRepository mbrUserMappingRepository;

    /**
     * 微信授权校验器
     */
    private final Consumer<MerchantId> checkWxAuthorization;

    @Autowired
    public MbrCardDomainService(MbrCouponRepository mbrCouponRepository, MbrConfigRepository mbrConfigRepository, MbrWxCardRepository mbrWxCardRepository, WXPublicUserInfoDalMapper wxPublicUserInfoDalMapper, MemberRedisDomainService memberRedisDomainService, MbrPayGiftCardRuleRepository mbrPayGiftCardRuleRepository, MbrOrderPayDalMapper mbrOrderPayDalMapper, MemberRepository memberRepository, MbrUserMappingRepository mbrUserMappingRepository) {
        this.mbrCouponRepository = mbrCouponRepository;
        this.mbrConfigRepository = mbrConfigRepository;
        this.mbrWxCardRepository = mbrWxCardRepository;
        this.wxPublicUserInfoDalMapper = wxPublicUserInfoDalMapper;
        this.memberRedisDomainService = memberRedisDomainService;
        this.mbrPayGiftCardRuleRepository = mbrPayGiftCardRuleRepository;
        this.mbrOrderPayDalMapper = mbrOrderPayDalMapper;
        this.memberRepository = memberRepository;
        this.mbrUserMappingRepository = mbrUserMappingRepository;

        //校验器初始化
        checkWxAuthorization = merchantId -> {
            AgentWXPublicUserInfo agentWXPublicUserInfo = wxPublicUserInfoDalMapper.selectByMerchantId(merchantId.getId());
            Assert.notNull(agentWXPublicUserInfo, "未授权微信公众号，无法使用该功能");
        };

    }

    /**
     * 添加微信基础信息
     *
     * @param createCard
     */
    public void createCard(CreateCard createCard) {

        //赠送卡券查询校验
        MbrCouponId mbrCouponId = new MbrCouponId(0L);
        if (createCard.getGiftCouponNumber() != null && !"".equals(createCard.getGiftCouponNumber())) {
            MbrCoupon mbrCoupon = mbrCouponRepository.fromCouponNumber(createCard.getGiftCouponNumber());
            Assert.notNull(mbrCoupon, "所选择赠送卡券不存在");
            mbrCouponId = mbrCoupon.getId();
        }

        //保存微信基础信息
        MbrConfig mbrConfig = mbrConfigRepository.findByMerchantId(createCard.getMerchantId());
        if (mbrConfig == null) {
            mbrConfig = new MbrConfig(
                    createCard.getMerchantId(),
                    createCard.getCardCoverChoice(),
                    createCard.getCardColour(),
                    createCard.getCardPicture(),
                    createCard.getCardName(),
                    createCard.getContactNumber(),
                    createCard.getCardPrivilegeExplain(),
                    createCard.getCardUseNotice(),
                    createCard.getGiftScore(),
                    mbrCouponId
            );
            mbrConfigRepository.save(mbrConfig);
        } else {
            mbrConfig.update(createCard.getCardCoverChoice(),
                    createCard.getCardColour(),
                    createCard.getCardPicture(),
                    createCard.getCardName(),
                    createCard.getContactNumber(),
                    createCard.getCardPrivilegeExplain(),
                    createCard.getCardUseNotice(),
                    createCard.getGiftScore(),
                    mbrCouponId
            );
            mbrConfigRepository.update(mbrConfig);
        }
    }

    /**
     * 修改会员基础信息
     *
     * @param updateCard
     */
    public void updateCard(UpdateCard updateCard) {

        //赠送卡券查询校验
        MbrCouponId mbrCouponId = new MbrCouponId(0L);
        if (updateCard.getGiftCouponNumber() != null && !"".equals(updateCard.getGiftCouponNumber())) {
            MbrCoupon mbrCoupon = mbrCouponRepository.fromCouponNumber(updateCard.getGiftCouponNumber());
            Assert.notNull(mbrCoupon, "所选择赠送卡券不存在");
            mbrCouponId = mbrCoupon.getId();
        }

        MbrConfig mbrConfig = mbrConfigRepository.fromId(updateCard.getMbrConfigId());
        Assert.notNull(mbrConfig, "会员信息不存在");
        mbrConfig.update(updateCard.getCardCoverChoice(),
                updateCard.getCardColour(),
                updateCard.getCardPicture(),
                updateCard.getCardName(),
                updateCard.getContactNumber(),
                updateCard.getCardPrivilegeExplain(),
                updateCard.getCardUseNotice(),
                updateCard.getGiftScore(),
                mbrCouponId
        );
        mbrConfigRepository.update(mbrConfig);
    }

    /**
     * 创建微信会员卡
     *
     * @param createWxCard
     */
    public void createWxCard(CreateWxCard createWxCard) {
        //关联信息查询 校验
        MbrWxCard mbrWxCard = mbrWxCardRepository.fromMerchantId(createWxCard.getMerchantId());
        if (mbrWxCard != null) {
            throw new IllegalStateException("微信会员信息已存在，请勿重复添加");
        }
        MbrConfig mbrConfig = mbrConfigRepository.findByMerchantId(createWxCard.getMerchantId());
        Assert.notNull(mbrConfig, "未添加会员基础信息");
        //保存微信会员卡信息
        mbrWxCard = new MbrWxCard(
                createWxCard.getMerchantId(),
                createWxCard.getShowEquityList(),
                createWxCard.getOperationInstruction(),
                createWxCard.getInterfaceSwitch(),
                createWxCard.getInterfaceName(),
                createWxCard.getInterfaceGuide(),
                createWxCard.getInterfaceUrl()
        );
        mbrWxCardRepository.save(mbrWxCard);
        //调用微信创建会员卡接口
        //判断是否 授权成功
        AgentWXPublicUserInfo agentWXPublicUserInfo = wxPublicUserInfoDalMapper.selectByMerchantId(createWxCard.getMerchantId().getId());
        Assert.notNull(agentWXPublicUserInfo, "未授权微信公众号，无法使用该功能");
        //accessToken获取
        String accessToken = memberRedisDomainService.getMerchantAccessToken(createWxCard.getMerchantId().getId());
        //请求微信
        CreateResult createResult = callWxCreateCard(mbrConfig.getCardCoverChoice(), mbrConfig.getCardPicture(), mbrWxCard.getShowEquityList(), accessToken, createWxCard.getLogoUrl(), agentWXPublicUserInfo.getHeadImg()
                , createWxCard.getMerchantName(), agentWXPublicUserInfo.getNickName(), mbrConfig.getCardUseNotice()
                , createWxCard.getInterfaceSwitch(), createWxCard.getInterfaceName(), createWxCard.getInterfaceUrl(), createWxCard.getInterfaceGuide()
                , mbrConfig.getCardPrivilegeExplain(), createWxCard.getMerchantId(), mbrWxCard.getOperationInstruction());
        //微信响应内容处理
        if (createResult.isSuccess()) {
            mbrConfig.setWxSyncSwitch(SwicthEnum.ON);
            mbrWxCard.auditing(createResult.getCardId());
        } else {
            mbrConfig.setWxSyncSwitch(SwicthEnum.OFF);
            mbrWxCard.auditFail(createResult.getErrmsg());
        }
        mbrConfigRepository.update(mbrConfig);
        mbrWxCardRepository.update(mbrWxCard);
    }

    public void updateWxCard(UpdateWxCard updateWxCard) {
        MbrWxCard mbrWxCard = mbrWxCardRepository.fromId(updateWxCard.getMbrWxCardId());
        Assert.notNull(mbrWxCard, "微信会员卡信息未查到");
        MbrConfig mbrConfig = mbrConfigRepository.findByMerchantId(mbrWxCard.getMerchantId());
        Assert.notNull(mbrConfig, "未添加会员基础信息");
        //保存微信会员卡信息
        mbrWxCard.update(
                updateWxCard.getShowEquityList(),
                updateWxCard.getOperationInstruction(),
                updateWxCard.getInterfaceSwitch(),
                updateWxCard.getInterfaceName(),
                updateWxCard.getInterfaceGuide(),
                updateWxCard.getInterfaceUrl()
        );
        mbrWxCardRepository.update(mbrWxCard);
        //判断是否开启同步微信会员卡
        //判断是否 授权成功
        AgentWXPublicUserInfo agentWXPublicUserInfo = wxPublicUserInfoDalMapper.selectByMerchantId(mbrConfig.getMerchantId().getId());
        Assert.notNull(agentWXPublicUserInfo, "未授权微信公众号，无法使用该功能");
        //accessToken获取
        String accessToken = memberRedisDomainService.getMerchantAccessToken(mbrConfig.getMerchantId().getId());
        //已经同步至微信会员卡,调用微信修改接口
        if (WxStatusEnum.AUDIT_SUCCESS.equals(mbrWxCard.getWxStatus())) {
            UpdateMemberCard updateMemberCard = new UpdateMemberCard();
            updateMemberCard.setCardId(mbrWxCard.getWxCardId());

            weixin.popular.bean.card.membercard.update.MemberCard memberCard = new weixin.popular.bean.card.membercard.update.MemberCard();
            if (CardCoverEnum.PICTURE.equals(mbrConfig.getCardCoverChoice())) {
                memberCard.setBackgroundPicUrl(WxUploadUtils.uploadWxLogo(accessToken, mbrConfig.getCardPicture()));
            }
            //设置显示类目
            mbrWxCard.getShowEquityList().forEach(showEquityEnum -> {
                switch (showEquityEnum) {
                    case AMOUNT:
                        CustomField customField1 = new CustomField();
                        customField1.setName("余额");
                        customField1.setUrl(memberH5Url + "/h5/mbr-wx-card/redirect/storeList");
                        memberCard.setCustomField1(customField1);
                        break;
                    case SCORE:
                        CustomField customField2 = new CustomField();
                        customField2.setName("积分");
                        customField2.setUrl(memberH5Url + "/h5/mbr-wx-card/redirect/pointList");
                        memberCard.setCustomField2(customField2);
                        break;
                    case COUPON:
                        CustomField customField3 = new CustomField();
                        customField3.setName("优惠券");
                        customField3.setUrl(memberH5Url + "/h5/mbr-wx-card/redirect/myCouponPackage");
                        memberCard.setCustomField3(customField3);
                        break;
                }
            });
            weixin.popular.bean.card.membercard.update.BaseInfo baseInfo = new weixin.popular.bean.card.membercard.update.BaseInfo();
            String logoUrl = updateWxCard.getLogoUrl();
            String wxLogoUrl;
            if (logoUrl != null && !"".equals(logoUrl)) {
                wxLogoUrl = WxUploadUtils.uploadWxLogo(accessToken, logoUrl);
            } else {
                wxLogoUrl = WxUploadUtils.uploadWxLogo(accessToken, agentWXPublicUserInfo.getHeadImg());
            }
            baseInfo.setLogoUrl(wxLogoUrl);
            baseInfo.setTitle(mbrConfig.getCardName());
            baseInfo.setDescription(mbrConfig.getCardUseNotice());
            baseInfo.setNotice(updateWxCard.getOperationInstruction());
            baseInfo.setServicePhone(mbrConfig.getContactNumber());
            baseInfo.setCenterSubTitle(mbrWxCard.getOperationInstruction());
            baseInfo.setCustomUrlName("会员中心");
            baseInfo.setCustomUrl(memberH5Url + "/h5/mbr-wx-card/redirect/index");
            if (mbrWxCard.getInterfaceSwitch().equals(SwicthEnum.ON)) {
                baseInfo.setPromotionUrlName(mbrWxCard.getInterfaceName());
                baseInfo.setPromotionUrl(mbrWxCard.getInterfaceUrl());
            }
            CustomCell customCell1 = new CustomCell();
            customCell1.setName("适用门店");
            customCell1.setUrl(memberH5Url + "/h5/mbr-wx-card/redirect/nearbyStores");
            memberCard.setCustomCell1(customCell1);

            memberCard.setBaseInfo(baseInfo);
            memberCard.setSupplyBonus(false);
            memberCard.setSupplyBalance(false);
            updateMemberCard.setMemberCard(memberCard);
            System.out.println(JsonUtil.toJSONString(updateMemberCard));
            UpdateResult updateResult = CardAPI.update(accessToken, updateMemberCard);
            if (updateResult.isSuccess()) {
                mbrConfig.setWxSyncSwitch(SwicthEnum.ON);
                mbrWxCard.auditing(mbrWxCard.getWxCardId());
                mbrConfigRepository.update(mbrConfig);
            } else {
                mbrConfig.setWxSyncSwitch(SwicthEnum.OFF);
                mbrWxCard.auditFail(updateResult.getErrmsg());
            }
            mbrWxCardRepository.update(mbrWxCard);
        }
        //微信任在审核中 不提交微信修改
        else if (WxStatusEnum.AUDITING.equals(mbrWxCard.getWxStatus())) {
            throw new BaseException("", "微信会员卡 在审核中，审核完成后再提交修改");
        }
        //微信同步会员卡失败，调用微信创建接口
        else {
            //请求微信
            CreateResult createResult = callWxCreateCard(mbrConfig.getCardCoverChoice(), mbrConfig.getCardPicture(), mbrWxCard.getShowEquityList(), accessToken, updateWxCard.getLogoUrl(), agentWXPublicUserInfo.getHeadImg()
                    , updateWxCard.getMerchantName(), agentWXPublicUserInfo.getNickName(), mbrConfig.getCardUseNotice()
                    , updateWxCard.getInterfaceSwitch(), updateWxCard.getInterfaceName(), updateWxCard.getInterfaceUrl(), updateWxCard.getInterfaceGuide()
                    , mbrConfig.getCardPrivilegeExplain(), mbrWxCard.getMerchantId(), mbrWxCard.getOperationInstruction());
            //微信响应内容处理
            if (createResult.isSuccess()) {
                mbrConfig.setWxSyncSwitch(SwicthEnum.ON);
                mbrWxCard.auditing(createResult.getCardId());
                mbrConfigRepository.update(mbrConfig);
            } else {
                mbrConfig.setWxSyncSwitch(SwicthEnum.OFF);
                mbrWxCard.auditFail(createResult.getErrmsg());
            }
            mbrWxCardRepository.update(mbrWxCard);
        }
    }

    /**
     * 同步微信会员信息
     *
     * @param merchantId
     * @return
     */
    public void syncWxStatus(MerchantId merchantId) {
        MbrConfig mbrConfig = mbrConfigRepository.findByMerchantId(merchantId);
        Assert.notNull(mbrConfig, "会员卡基础信息不存在");
        MbrWxCard mbrWxCard = mbrWxCardRepository.fromMerchantId(merchantId);
        //若微信状态 为审核中，主动查询并同步状态
        if (mbrWxCard != null && WxStatusEnum.AUDITING.equals(mbrWxCard.getWxStatus())) {
            String accessToken = memberRedisDomainService.getMerchantAccessToken(merchantId.getId());
            GetResult getResult = CardAPI.getByCardId(accessToken, mbrWxCard.getWxCardId());
            if (getResult.isSuccess()) {
                GetMemberCardResult getMemberCardResult = (GetMemberCardResult) getResult;
                mbrWxCard.setWxStatus(WxStatusEnum.fromWxStatus(getMemberCardResult.getCard().getMemberCardDetail().getBaseInfo().getStatus()));
                mbrWxCardRepository.update(mbrWxCard);
            }
        }
    }

    public void wxCardAuditSuccess(String wxCardId) {
        MbrWxCard mbrWxCard = mbrWxCardRepository.fromWxCardId(wxCardId);
        mbrWxCard.auditSuccess();
        mbrWxCardRepository.update(mbrWxCard);
    }

    public void wxCardAuditFail(String wxCardId, String refuseReason) {
        MbrWxCard mbrWxCard = mbrWxCardRepository.fromWxCardId(wxCardId);
        mbrWxCard.auditFail(refuseReason);
        mbrWxCardRepository.update(mbrWxCard);
    }

    /**
     * 判断能否同步微信
     *
     * @param merchantId
     */
    public SwicthEnum canSyncWx(MerchantId merchantId) {
        MbrConfig mbrConfig = mbrConfigRepository.findByMerchantId(merchantId);
        Assert.notNull(mbrConfig, "未添加会员基础信息");
        //判断是否 授权成功
        checkWxAuthorization.accept(merchantId);
        return mbrConfig.getWxSyncSwitch();
    }

    /**
     * 处理同步至微信会员卡包 操作
     *
     * @param merchantId
     * @param wxSyncSwitch
     */
    public void updateSyncWxSwitch(MerchantId merchantId, SwicthEnum wxSyncSwitch) {
        MbrConfig mbrConfig = mbrConfigRepository.findByMerchantId(merchantId);
        Assert.notNull(mbrConfig, "未添加会员基础信息");
        //判断是否 授权成功
        checkWxAuthorization.accept(merchantId);
        MbrPayGiftCardRule mbrPayGiftCardRule = mbrPayGiftCardRuleRepository.findByMerchantId(merchantId);
        //accessToken获取
        String accessToken = memberRedisDomainService.getMerchantAccessToken(mbrConfig.getMerchantId().getId());
        MbrWxCard mbrWxCard = mbrWxCardRepository.fromMerchantId(merchantId);
        Assert.notNull(mbrWxCard, "微信会员卡信息不存在");
        //要开启同步微信，但是微信审核并未通过 不做处理
        if (SwicthEnum.ON.equals(wxSyncSwitch) && !WxStatusEnum.AUDIT_SUCCESS.equals(mbrWxCard.getWxStatus())) {
            return;
        }
        mbrConfig.setWxSyncSwitch(wxSyncSwitch);
        mbrConfigRepository.update(mbrConfig);
    }


    /**
     * 判断是否符合支付即会员
     *
     * @param orderNumber
     * @param merchantId
     */
    public String canGiftCard(String orderNumber, MerchantId merchantId, String openId) {
        OrderPay orderPay = mbrOrderPayDalMapper.selectByOrderNumber(orderNumber);
        Assert.notNull(orderPay, "未查到该笔订单");
        if (!mbrUserMappingRepository.checkOpenId(openId)) {
            throw new BaseException("", "该用户已经是会员");
        }
        MbrPayGiftCardRule mbrPayGiftCardRule = mbrPayGiftCardRuleRepository.findByMerchantId(merchantId);
        Assert.notNull(mbrPayGiftCardRule, "未设置支付即会员规则");
        MbrConfig mbrConfig = mbrConfigRepository.findByMerchantId(merchantId);
        Assert.notNull(mbrConfig, "未查到微信基础信息");
        LocalDateTime beginTime = LocalDateTime.ofInstant(mbrPayGiftCardRule.getBeginTime().toInstant(), ZoneId.systemDefault());
        LocalDateTime endTime = LocalDateTime.ofInstant(mbrPayGiftCardRule.getEndTime().toInstant(), ZoneId.systemDefault());
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(beginTime) || now.isAfter(endTime)) {
            throw new BaseException("", "订单不在支付即会员指定有效时间内");
        }
        if (orderPay.getAmount().compareTo(mbrPayGiftCardRule.getLeastCost()) == -1) {
            throw new BaseException("", "订单金额小于支付即会员下限");
        }
//        if (orderPay.getAmount().compareTo(mbrPayGiftCardRule.getMaxCost()) != -1) {
//            throw new BaseException("", "订单金额大于支付即会员上限");
//        }
        return mbrConfig.getCardName();
    }


    /**
     * 请求微信创建卡券
     *
     * @param accessToken
     * @param logoUrl
     * @param headImg
     * @param merchantName
     * @param title
     * @param cardUseNotice
     * @param interfaceSwitch
     * @param interfaceName
     * @param interfaceUrl
     * @param interfaceGuide
     * @param cardPrivilegeExplain
     * @return
     */
    private CreateResult callWxCreateCard(CardCoverEnum cardCoverChoice, String cardPicture, List<ShowEquityEnum> showEquityList, String accessToken, String logoUrl, String headImg, String merchantName, String title
            , String cardUseNotice, SwicthEnum interfaceSwitch, String interfaceName, String interfaceUrl, String interfaceGuide
            , String cardPrivilegeExplain, MerchantId merchantId, String operationInstruction) {
        if (memberH5Url == null || "".equals(memberH5Url)) {
            throw new BaseException("", "会员H5域名未配置");
        }
        //微信请求封装
        MemberCard memberCard = new MemberCard();
        MemberCardDetail memberCardDetail = new MemberCardDetail();
        if (CardCoverEnum.PICTURE.equals(cardCoverChoice)) {
            memberCardDetail.setBackgroudPicUrl(WxUploadUtils.uploadWxLogo(accessToken, cardPicture));
        }
        BaseInfo baseInfo = new BaseInfo();
        //会员卡头像处理
        String wxLogoUrl;
        if (logoUrl == null || "".equals(logoUrl)) {
            wxLogoUrl = WxUploadUtils.uploadWxLogo(accessToken, headImg);
        } else {
            wxLogoUrl = WxUploadUtils.uploadWxLogo(accessToken, logoUrl);
        }
        baseInfo.setLogoUrl(wxLogoUrl);
        baseInfo.setBrandName(merchantName);
        baseInfo.setCodeType("CODE_TYPE_QRCODE");
        baseInfo.setTitle(title);
        baseInfo.setColor("Color080");
        baseInfo.setNotice("卡券使用提醒");
        baseInfo.setDescription(cardUseNotice);
        DateInfo dateInfo = new DateInfo();
        dateInfo.setType("DATE_TYPE_PERMANENT");
        baseInfo.setDateInfo(dateInfo);
        Sku sku = new Sku();
        sku.setQuantity(50000000);
        baseInfo.setSku(sku);
        baseInfo.setUseCustomCode(true);
        baseInfo.setCanGiveFriend(false);
        baseInfo.setCenterTitle("快速充值");
        baseInfo.setCenterUrl(memberH5Url + "/h5/mbr-wx-card/redirect/rechargeRule");
        baseInfo.setCenterSubTitle(operationInstruction);
        baseInfo.setCustomUrlName("会员中心");
        baseInfo.setCustomUrl(memberH5Url + "/h5/mbr-wx-card/redirect/index");

        if (interfaceSwitch.equals(SwicthEnum.ON)) {
            baseInfo.setPromotionUrlName(interfaceName);
            baseInfo.setPromotionUrl(interfaceUrl);
        }
        baseInfo.setNeedPushOnView(false);
        memberCardDetail.setBaseInfo(baseInfo);
        AdvancedInfo advancedInfo = new AdvancedInfo();
        memberCardDetail.setAdvancedInfo(advancedInfo);
        memberCardDetail.setSupplyBonus(false);
        memberCardDetail.setSupplyBalance(false);
        memberCardDetail.setPrerogative(cardPrivilegeExplain);

        //设置显示类目
        showEquityList.forEach(showEquityEnum -> {
            switch (showEquityEnum) {
                case AMOUNT:
                    CustomField customField1 = new CustomField();
                    customField1.setName("余额");
                    customField1.setUrl(memberH5Url + "/h5/mbr-wx-card/redirect/storeList");
                    memberCardDetail.setCustomField1(customField1);
                    break;
                case SCORE:
                    CustomField customField2 = new CustomField();
                    customField2.setName("积分");
                    customField2.setUrl(memberH5Url + "/h5/mbr-wx-card/redirect/pointList");
                    memberCardDetail.setCustomField2(customField2);
                    break;
                case COUPON:
                    CustomField customField3 = new CustomField();
                    customField3.setName("优惠券");
                    customField3.setUrl(memberH5Url + "/h5/mbr-wx-card/redirect/myCouponPackage");
                    memberCardDetail.setCustomField3(customField3);
                    break;
            }
        });

        memberCardDetail.setActivateUrl(memberH5Url + "/h5/mbr-wx-card/activation-wx-card");
        CustomCell customCell1 = new CustomCell();
        customCell1.setName("适用门店");
        customCell1.setUrl(memberH5Url + "/h5/mbr-wx-card/redirect/nearbyStores");
        memberCardDetail.setCustomCell1(customCell1);


        memberCard.setMemberCardDetail(memberCardDetail);
        CreateResult createResult = CardAPI.create(accessToken, memberCard);
        return createResult;
    }

    /**
     * 同步积分余额 至 微信
     */
    public void syncScoreAmountToWx(MerchantId merchantId, MbrAccount mbrAccount) {
        Member member = memberRepository.fromId(mbrAccount.getMemberId());
        if (member != null) {
            MbrWxCard mbrWxCard = mbrWxCardRepository.fromMerchantId(merchantId);

            if (SwicthEnum.ON.equals(member.getSyncWxStatus())) {
                String accessToken = memberRedisDomainService.getMerchantAccessToken(merchantId.getId());
                if (accessToken == null) {
                    log.error("【同步微信会员信息】：获取accesstoken失败  merchant_id:{}", merchantId.getId());
                }
                UpdateMemberInfo updateMemberInfo = new UpdateMemberInfo();
                updateMemberInfo.setCode(member.getMemberCardNum());
                updateMemberInfo.setCardId(mbrWxCard.getWxCardId());
                updateMemberInfo.setBonus(BigDecimal.valueOf(mbrAccount.getAvailableScore()));
                updateMemberInfo.setBalance(mbrAccount.getAvailableBalance());
                UpdateMemberInfoResult updateMemberInfoResult = CardAPI.updateMemberInfo(accessToken, updateMemberInfo);
                if (!updateMemberInfoResult.isSuccess()) {
                    //TODO 微信请求补偿机制
                }

            }
        } else {
            log.error("【同步微信会员信息】：未查到会员信息 member_id:{}", mbrAccount.getMemberId().getId());
        }

    }


}
